package com.egao.common.manage.school;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egao.common.core.Constants;
import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.manage.TableStatistics;
import com.egao.common.module.company.constants.CompanyConstants;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.vo.CompanyCheckRecordListVO;
import com.egao.common.module.company.entity.vo.CompanyFormVO;
import com.egao.common.module.company.entity.vo.CompanyListVO;
import com.egao.common.module.company.service.CompanyCheckRecordService;
import com.egao.common.module.company.service.CompanyQuestionService;
import com.egao.common.module.company.service.CompanyService;
import com.egao.common.module.student.entity.vo.StudentSignRecordVO;
import com.egao.common.module.student.service.StudentSignService;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.title;

/**
 * 学校单位管理
 * @author dl
 */
@Api(tags = "学校单位管理")
@RestController
@RequestMapping("${api}")
public class SchoolCompanyController extends BaseController {

    @Autowired
    private CompanyService companyService;
    @Autowired
    private StudentSignService studentSignService;
    @Autowired
    private UserService userService;

    @Autowired
    private CompanyCheckRecordService checkRecordService;

    @Autowired
    private CompanyQuestionService companyQuestionService;


    @PreAuthorize("hasAuthority('school:company:list')")
    @ApiOperation(value = "分页查询单位", notes = "未审核状态升序 创建时间倒序")
    @OperLog(value = "学校单位管理", desc = "分页查询单位")
    @ApiPageParam
    @GetMapping("/school/company/page")
    public PageResult<CompanyListVO> page(HttpServletRequest request) {
        PageParam<CompanyListVO> pageParam = new PageParam<>(request);
        return new PageResult<>(companyService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('school:company:detail')")
    @ApiOperation(value = "获取单位详情")
    @OperLog(value = "学校单位管理", desc = "获取单位详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "单位id", required = true, dataType = "int")
    })
    @GetMapping("/school/company/detail")
    public JsonResult detail(Integer id) {
        return companyService.detail(id);
    }

    @PreAuthorize("hasAuthority('school:company:update')")
    @OperLog(value = "学校单位管理", desc = "编辑审核单位信息", result = true)
    @ApiOperation(value = "编辑审核单位信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "company", value = "company", required = true, dataType = "Company")
    })
    @PutMapping("/school/company/update")
    public JsonResult update(@RequestBody CompanyFormVO companyFormVO) {
        companyFormVO.setCheckUserId(getLoginUserId());
        return companyService.checkCompany(companyFormVO);
    }

    @PreAuthorize("hasAuthority('school:company:dict')")
    @OperLog(value = "学校单位管理", desc = "获取单位字典")
    @ApiOperation(value = "获取单位字典")
    @GetMapping("/school/company/dict")
    public JsonResult getCompanyDict() {
        return companyService.getCompanyDict();
    }

    @PreAuthorize("hasAuthority('school:company:update_recruit_flag')")
    @OperLog(value = "学校单位管理", desc = "修改单篇状态", result = true)
    @ApiOperation(value = "修改单篇状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "单位id", required = true, dataType = "int")
    })
    @PutMapping("/school/company/updateRecruitFlag")
    public JsonResult updateRecruitFlag(@RequestBody CompanyFormVO companyFormVO) {
        return companyService.updateRecruitFlag(companyFormVO.getId());
    }

    @PreAuthorize("hasAuthority('school:company:delete')")
    @OperLog(value = "学校单位管理", desc = "修改状态", result = true)
    @ApiOperation(value = "修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "单位id", required = true, dataType = "int")
    })
    @PutMapping("/school/company/delete")
    public JsonResult delete(@RequestBody CompanyFormVO companyFormVO) {
        return companyService.deleteFlag(companyFormVO.getId(), companyFormVO.getDeleted(), companyFormVO.getUserId());
    }

    @PreAuthorize("hasAuthority('school:company:list')")
    @ApiOperation(value = "分页查询单位", notes = "未审核状态升序 创建时间倒序")
    @OperLog(value = "学校单位管理", desc = "分页查询单位")
    @ApiPageParam
    @GetMapping("/school/company/check-record")
    public PageResult<CompanyCheckRecordListVO> pageCheckRecord(HttpServletRequest request) {
        PageParam<CompanyCheckRecordListVO> pageParam = new PageParam<>(request);
        return new PageResult<>(checkRecordService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('school:company:list')")
    @ApiOperation(value = "查询单位签约记录", notes = "签约时间倒叙")
    @OperLog(value = "学校单位管理", desc = "查询单位签约记录")
    @ApiPageParam
    @GetMapping("/school/company/sign-record")
    public PageResult<StudentSignRecordVO> signRecord(HttpServletRequest request) {
        PageParam<StudentSignRecordVO> pageParam = new PageParam<>(request);
        return studentSignService.listSignRecord(pageParam);
    }

    @PreAuthorize("hasAuthority('school:company:update')")
    @OperLog(value = "单位管理", desc = "修改单位用户状态", result = true)
    @ApiOperation("修改单位用户状态")
    @PutMapping("/school/company/user-state/{userId}")
    public JsonResult updateState(@PathVariable("userId") Integer userId, Integer state) {
        if (state == null || (state != 0 && state != 1)) {
            return JsonResult.error("状态值不正确");
        }
        String message = "锁定";
        User user = new User();
        user.setUserId(userId);
        user.setState(state);
        user.setLoginCount(0);
        if (Constants.USER_STATE.equals(state)) {
            user.setLoginCount(0);
            message = "解锁";
        }
        if (userService.updateById(user)) {
            return JsonResult.ok(message + "成功");
        }
        return JsonResult.error(message + "失败");
    }

    @PreAuthorize("hasAuthority('school:company:list')")
    @ApiOperation(value = "列表统计")
    @GetMapping("/school/company/statistics")
    public JsonResult statistics() {
        List<Company> list = companyService.list(new LambdaQueryWrapper<Company>()
                .select(Company::getState, Company::getHbIndustry, Company::getAlumniState)
        );

        long wait = list.stream().filter(d -> CompanyConstants.COMPANY_STATE_WAIT.equals(d.getState())).count();
        long pass = list.stream().filter(d -> CompanyConstants.COMPANY_STATE_PASS.equals(d.getState())).count();
        long failed = list.stream().filter(d -> CompanyConstants.COMPANY_STATE_FAILED.equals(d.getState())).count();
        long hbIndustry = list.stream().filter(d -> "0".equals(d.getHbIndustry())).count();
        long alumniState = list.stream().filter(d -> "0".equals(d.getAlumniState())).count();

        List<TableStatistics> table = new ArrayList<>();
        table.add(new TableStatistics(1, "待审核单位", wait));
        table.add(new TableStatistics(2, "审核通过单位", pass));
        table.add(new TableStatistics(3, "审核未通过单位", failed));
        table.add(new TableStatistics(4, "湖北重点产业单位", hbIndustry));
        table.add(new TableStatistics(5, "校友单位", alumniState));

        return JsonResult.ok().setData(table);
    }

    @PreAuthorize("hasAuthority('school:company:list')")
    @ApiOperation(value = "查询单位名称")
    @GetMapping("/school/company/name")
    public JsonResult name(String name) {
        if (StrUtil.isBlank(name)) {
            return JsonResult.ok();
        }
        List<Company> list = companyService.list(new LambdaQueryWrapper<Company>()
                .select(Company::getName)
                .like(Company::getName, name)
        );

        return JsonResult.ok().setData(list);
    }

    @PreAuthorize("hasAuthority('school:company:list')")
    @ApiOperation(value = "导出")
    @GetMapping("/school/company/questionnaire/export")
    public void export(HttpServletResponse response) {
        companyQuestionService.exportExcel(response);
    }

    @PreAuthorize("hasAuthority('school:company:list')")
    @ApiOperation(value = "统计企业问卷")
    @GetMapping("/school/company/questionnaire/statistics")
    public JsonResult statisticsCompanyQuestionnaire() {
        return JsonResult.ok().setData(companyQuestionService.statistics());
    }
}
